import { Component, OnInit } from '@angular/core';
import {FormBuilder, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {environment} from "../../../environments/environment";
import {ProcessService} from "../process.service";
import {StorageService} from "../../services/storage.service";
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-construction-completed',
  templateUrl: './construction-completed.component.html',
  styleUrls: ['./construction-completed.component.scss']
})
export class ConstructionCompletedComponent implements OnInit {
  constructionForm;
  fb: FormBuilder = new FormBuilder();
  showAddConstruction: boolean = false;
  tabs;
  cols;
  asscitedCols;
  OperationLogCols;
  sid;
  approvedModel;
  currentContruction =[];
  dataSource;
  devices;
  totalRecords;
  tabIndex = 0;
  radioButton = [] ;
  file;
  approvedProcess;
  operations;
  treeModel;

  tableDatas;
  dropDownData;
  ip;
  optButtons;
  affected_location = [];
  location = [];

  constructor(
    private route: ActivatedRoute,
    private router:Router,
    private processService: ProcessService,
    private storageService:StorageService,
    private eventBusService:EventBusService

  ) { }

  ngOnInit() {
    this.tabs = [
      {label:'基本信息'},
      {label:'审批信息'},
      {label:'操作日志'}
    ];
    this.cols = [
      {field: 'ano', header: '设备编号'},
      {field: 'name', header: '设备名称'},
      {field: 'modle', header: '设备型号'},
      {field: 'location', header: '设备位置'},
      {field: 'manager', header: '责任人'},
      {field: 'status', header: '设备状态'},
    ];
    //审批页面审批信息
    this.asscitedCols = [
      {field: 'approve_time', header: '审批时间'},
      {field: 'approver', header: '审批人'},
      {field: 'approve_status', header: '审批状态'},
      {field: 'approve_remarks', header: '审批意见'},
      {field: 'approver', header: '责任人'},
    ];
    //审批页面操作日志
    this.OperationLogCols = [
      {field: 'operate_time', header: '操作时间'},
      {field: 'operator', header: '操作人'},
      {field: 'operate_content', header: '操作内容'},
      {field: 'operate_description', header: '操作说明'},
    ];
    this.constructionForm = this.fb.group({
      "sid": [''],  //施工单号
      "status": [''],  //状态
      "creator":[''],    //受理人
      "create_time":[''],   //受理时间
      "submitter":[''],   //申请人
      "submit_time":[''], //申请时间
      "submitter_org":'',  //所属组织
      "construction_plantime_start":'', //计划开始时间
      "submitter_phone":'', //电话
      "construction_plantime_end":'', //计划结束时间
      "construction_type":'', //施工类型
      "org_approver":'', //部门审批人
      "is_affected":'', //影响业务
      "construction_affecttime_start":'', //影响时间
      "construct_location":[], //施工区域
      "affected_location":[], //影响区域
      "construction_content":'', //施工内容
      "construction_description":'', //施工内容详述
      "construction_apply_attachments":[], //上传附件
      "construction_acttime_start":[], //实施开始时间
      "construction_acttime_end":[], //预计结束时间
      "constructor_unit":[], //实施单位
      "constructor_per":[], //实施人员
      "construction_finish_description":"", //施工结果描述
      "reviewor":[], //复核人
      "review_time":[], //复核时间
      "review_opinion":[], //复核说明
      "close_code":[], //结束代码
      "close_time":[], //结束时间

    });
    this.approvedModel = {
      "sid": "",
      "status": "",
      "constructor_name":"",
      "constructor_pid": "",
      "constructor_unit": "",
      "constructor_unit_id": "",
      "construction_finish_description": "",
      "construction_acttime_start": "",
      "construction_acttime_end": "",
      "construction_finish_attachments": [],
    };
    this.optButtons=[
      {label:'提交',status:'待复核'},
      // {label:'保存',status:'待施工'},
    ]
    this.ip = environment.url.management;
    this.treeModel={
      oid:""
    }

    this.radioButton = [
      {label:'影响业务',value:true},
      {label:'不影响业务',value:false}
    ];
    this.queryConstructionApproved();
  }
  showAddConstructionMask(){
    this.showAddConstruction = !this.showAddConstruction;
  }
  closeConstruction(bool){
    this.showAddConstruction = bool;
  }
  addPlanOrg(org){
    this.approvedModel.constructor_unit_id=[] ;
    this.approvedModel.constructor_unit = [];
    this.treeModel.oid =  this.approvedModel.constructor_unit_id;
    console.log(this.treeModel.oid)
    for(let i = 0;i<org.length;i++){
      this.approvedModel.constructor_unit_id.push(org[i]['oid'])
      this.approvedModel.constructor_unit.push(org[i]['label'])
    }
    this.approvedModel.constructor_unit =  this.approvedModel.constructor_unit.join(',');
    this.showAddConstruction = false;
    this.queryJurList('');
  }
  clearTreeDialog () {
    this.approvedModel.constructor_unit = '';
    this.approvedModel.constructor_unit_id = [];
  }
  //查询人员表格数据
  queryJurList(oid){
      this.processService.getJurList(this.treeModel.oid).subscribe(data => {
        this.tableDatas = data;
        console.log(this.tableDatas);
        this.dropDownData = this.processService.applicationDropdownapprover(this.tableDatas);
        this.approvedModel.constructor_name = this.dropDownData[0]['label']
        this.approvedModel.constructor_pid = this.dropDownData[0]['value']
      })


  }
  onBeforeUpload(event) {
    let token = this.storageService.getToken('token');
    event.formData.append('access_token', token);
  }
  onUpload(event) {
    let xhrRespose = JSON.parse(event.xhr.response);
    if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
      this.approvedModel.construction_finish_attachments = xhrRespose['datas'];
      // this.message = [];
      // this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
    }else {
      // this.message = [];
      // this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
    }
  }
//文件上传
  onBasicUploadAuto(event) {
    let res = JSON.parse(event.xhr.responseText);
    let photoUrl = res['datas'];
    console.log(photoUrl);
    let construction_finish_attachments = [];
    for(let i = 0;i<photoUrl.length;i++){
      let temp = photoUrl[i];
      console.log(temp)
      let obj ={};
      obj['path'] = temp['path'];
      obj['file_name'] = temp['file_name'];
      obj['file_size'] = temp['file_size'];
      obj['upload_time'] = temp['upload_time'];
      construction_finish_attachments.push(obj);
    }
    this.approvedModel.construction_finish_attachments = construction_finish_attachments;
    console.log( this.approvedModel.construction_finish_attachments)
  }
  queryConstructionApproved(){
    this.route.queryParams.subscribe(parms=>{
      if(parms['sid']){
        this.sid =parms['sid'];
      }
      this.approvedModel.sid = this.sid;
      this.processService.constructionShow(this.sid).subscribe(data=>{
        this.currentContruction = data;
        this.approvedProcess = this.currentContruction['approval_process'];
        this.operations = this.currentContruction['operations'];
        this.dataSource = this.currentContruction['devices'];
        this.approvedModel.construction_acttime_start = this.currentContruction['construction_acttime_start'];
        this.approvedModel.construction_acttime_end = this.currentContruction['construction_acttime_end'];
        this.radioButton['value'] = this.currentContruction['is_affected'];
        this.file = this.currentContruction['construction_apply_attachments'];
        this.currentContruction['construct_location'].map((item,index)=>{
          this.location.push(item.label);
          this.currentContruction['construct_location'] = this.location
        })
        this.currentContruction['affected_location'].map((item,index)=>{
          this.affected_location.push(item.label);
          this.currentContruction['affected_location'] = this.affected_location
        })
        if(!this.dataSource){
          this.dataSource = [];
          this.totalRecords = 0;
        }
        this.totalRecords = this.dataSource.length;
        this.devices = this.dataSource.slice(0,10);
      })
    });
  }
  submitapprovedOption(status){
    this.approvedModel.status = status;
    this.currentContruction['status'] = '';
    this.eventBusService.flow.next(this.currentContruction['status']);
    this.processService.completedConstruction(this.approvedModel).subscribe(() =>{
      this.router.navigate(['../constructionoverview'],{relativeTo:this.route});
    })
  }

  changeTab(index){
    this.tabIndex = index;
  }
  goBack() {
    let sid =  this.currentContruction['sid'];
    this.currentContruction['status'] = "";
    this.eventBusService.flow.next(this.currentContruction['status']);
    this.router.navigate(['../constructionoverview'],{queryParams:{sid:sid,state:'viewDetail',title:'施工总览'},relativeTo:this.route})
  }
  download() {
    // window.open(`${environment.url.management}/${this.file.path}`, '_blank');
    window.open(`${environment.url.management}/data/file/workflow/construction/报障管理技术设计文档(1).doc_1522139592`, '_blank');

  }

}
